<template>
	<jk-dialog
		v-model="showDialog"
		title="批量导入-管圈颜色"
		width="900px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="confirmBtnLoading"
		append-to-body
		:permission-prefix="permissionPrefix"
		:show-custom-btn="false"
		:show-confirm-btn="false"
		:show-update-audit-btn="false"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<div ref="box1">
			<div class="flex-center margin-bottom-10">
				<upload-excel size="mini" type="primary" class="item-gap" icon="el-icon-plus" :plain="false" text="选择文件" :on-success="handleSuccess" :before-upload="beforeUpload"></upload-excel>
			</div>
			<el-alert :closable="false" title="" :type="tableData.filter(x => x.nameRepetition).length ? 'warning' : 'info'" class="margin-bottom-4" show-icon>
				<div class="flex-start-center">
					<span>
						一共
						<b style="font-size: 14px;">{{ tableData.length }}</b>
						条数据, 其中
						<b style="font-size: 14px;">{{ tableData.filter(x => x.nameRepetition).length }}</b>
						条已存在！
					</span>
					<el-button type="text" size="mini" @click="onDownDemo">下载导入模版</el-button>
				</div>
			</el-alert>
		</div>
		<jk-table ref="jkTable" border :loading="validateLoading" :data="tableData" :height="dialogTableHeight - 30">
			<vxe-column title="操作" align="center" field="operation" :width="70">
				<template slot="header" slot-scope="scope">
					<el-popover trigger="click">
						<el-button size="mini" @click="tableData = [];">全部清空</el-button>
						<el-button size="mini" @click="tableData = tableData.filter(x => !x.nameRepetition)">保留可创建</el-button>
						<span slot="reference" style="color: #2d8cf0;cursor: pointer;">过滤</span>
					</el-popover>
				</template>
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-delete-solid" @click="tableData.splice(scope.rowIndex, 1)"></el-button>
				</template>
			</vxe-column>
			<vxe-column title="状态" align="center" field="nameRepetition" :width="90">
				<template slot-scope="scope">
					<el-tag :type="scope.row.nameRepetition ? 'warning' : 'success'" :class="scope.row.nameRepetition ? 'el-icon-warning-outline' : 'el-icon-check'" size="small" effect="plain">{{ scope.row.nameRepetition ? '已存在' : '可创建' }}</el-tag>
				</template>
			</vxe-column>
			<vxe-column title="名称" align="left" field="name" :min-width="140">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.name" placeholder="" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="类型" align="left" field="processName" :min-width="140">
				<template slot="header" slot-scope="scope">
					<div>
						<span class="item-gap">类型</span>
						<el-popover v-model="showTypePopover" trigger="click">
							<el-select v-model="tableHeaderInfo.typeId" clearable size="mini" placeholder="类型" @change="onAllTypeChange">
								<el-option
									v-for="item in typeList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								></el-option>
							</el-select>
							<span slot="reference" class="el-icon-edit-outline write-all-row-icon"></span>
						</el-popover>
					</div>
				</template>
				<template slot-scope="scope">
					<el-select v-model="scope.row.typeId" clearable size="mini" class="width-100-percent" placeholder="类型" @change="onTypeChange($event, scope)">
						<el-option
							v-for="item in typeList"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						></el-option>
					</el-select>
				</template>
			</vxe-column>
			<vxe-column title="状态" align="center" field="auditState" :width="80">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.auditState"
						active-color="#13ce66"
						inactive-color="#ff4949"
					></el-switch>
				</template>
			</vxe-column>
		</jk-table>
		<div ref="box2" class="flex-center margin-top-10">
			<jk-button :disabled="!tableData.length" :loading="validateLoading" type="primary" icon="el-icon-cpu" class="margin-right-10" size="small" @click="onValidateData">校验</jk-button>
			<jk-button :disabled="!tableData.length" :loading="confirmBtnLoading" type="success" icon="el-icon-position" size="small" @click="onConfirmBtn">提交</jk-button>
		</div>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import uploadExcel from '../../../components/UploadExcel/index';
    import { tipsBar, validateTableFormData } from '../../../utils/jk/jk-tool';
    import { spinTubeColorBatchCreate, spinTubeColorBatchValid } from '../../../api/basicData/tubeColor';
    export default {
        name: 'ImportCustomer',
        components: { uploadExcel },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                validateLoading: false,
                showTypePopover: false,
                showUnitPopover: false,
                tableHeaderInfo: {
                    typeId: null
                },
                tableData: [],
                tableLoading: false,
                typeList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false
            };
        },
        methods: {
            onDownDemo() {
                const a = document.createElement('a');
                a.href = '/import-template/管圈颜色-导入模版.xlsx';
                a.download = '管圈颜色-导入模版.xlsx';
                a.style.display = 'none';
                a.click();
                window.URL.revokeObjectURL(a.href);
            },
            onValidateData() {
                const arr = this.getParamData();
                this.validRequest(arr);
            },
            onAllTypeChange(e) {
                const item = this.typeList.find(x => x.id === e) || {};
                this.tableData.forEach(x => {
                    this.$set(x, 'typeId', item.id);
                    this.$set(x, 'typeName', item.name);
                });
                this.showTypePopover = false;
            },
            onTypeChange(e, scope) {
                const item = this.typeList.find(x => x.id === e) || {};
                this.$set(this.tableData[scope.rowIndex], 'typeId', item.id);
                this.$set(this.tableData[scope.rowIndex], 'typeName', item.name);
            },
            validRequest(arr) {
                this.validateLoading = true;
                spinTubeColorBatchValid(arr).then(res => {
                    this.validateLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res.map(x => {
                            x.auditState = !!x.auditState;
                            return x;
                        });
                    }
                });
            },
            handleSuccess({ results, header }) {
                const headerObj = {
                    '名称': 'name',
                    '圈管类型': 'typeName'
                };
                results.unshift(headerObj);
                const arr = this.setList(results).map(x => {
                    const typeItem = this.typeList.find(k => k.name === x.typeName) || {};
                    x.typeId = typeItem.id;
                    x.typeName = typeItem.name;
                    x.nameRepetition = false;
                    x.auditState = 1;
                    return x;
                });

                this.validRequest(arr);
            },
            setList(arr) {
                const [one, ...rest] = arr;
                const keys = Object.keys(one);
                const newRest = rest.map(item => {
                    const newObj = {};
                    keys.map(key => {
                        newObj[one[key]] = item[key];
                    });
                    return newObj;
                });
                return newRest;
            },
            beforeUpload(file) {
                const isLt1M = file.size / 1024 / 1024 < 10;
                if (isLt1M) {
                    return true;
                }

                this.$message({
                    message: 'Please do not upload files larger than 10M in size.',
                    type: 'warning'
                });
                return false;
            },
            getParamData() {
                const arr = JSON.parse(JSON.stringify(this.tableData));
                arr.forEach(x => {
                    x.auditState = x.auditState ? 1 : 0;
                });
                return arr;
            },
            createAndUpdateRequest() {
                this.confirmBtnLoading = true;
                spinTubeColorBatchCreate(this.getParamData()).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                if (validateTableFormData(this.tableData, ['name'])) {
                    const pass = this.tableData.some(x => x.nameRepetition);
                    if (!pass) {
                        this.createAndUpdateRequest();
                    } else {
                        tipsBar(this, 'custom', 'warning', '存在重复数据，请处理后在提交!');
                    }
                } else {
                    this.$tipsBar(this, 'validator');
                }
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            getTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'GQ_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getTypeListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped>
.write-all-row-icon:hover {
    cursor: pointer;
    color: #2d8cf0;
}
</style>
